package com.jwm.client.soft;

import cn.hutool.json.JSONUtil;
import com.jwm.model.App;
import com.jwm.model.TomcatVo;
import com.jwm.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.lang.management.MemoryUsage;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 崔洁
 */
@Component
public class TomcatTool {
    private static final Logger logger = LoggerFactory.getLogger(FileTool.class);

    public TomcatVo getInfo(App appVo) {
        logger.info("客户端 -> 获取Tomcat信息\n{}", JSONUtil.toJsonStr(appVo));
        TomcatVo tomcatVo = new TomcatVo();
        tomcatVo.setName(appVo.getName());
        tomcatVo.setPath(appVo.getPath());
        tomcatVo.setLogPath(appVo.getLogPath());
        tomcatVo.setTime(DateUtils.dateTimeNow());
        try {
            String jmxURL = "service:jmx:rmi:///jndi/rmi://localhost:" + appVo.getPort() + "/jmxrmi";
            JMXServiceURL serviceURL = new JMXServiceURL(jmxURL);
            Map<String, Object> auth = new HashMap<>();
            auth.put(JMXConnector.CREDENTIALS, new String[]{"cuijie", "cuijie1000"});
            JMXConnector connector = JMXConnectorFactory.connect(serviceURL, auth);
            MBeanServerConnection mbsc = connector.getMBeanServerConnection();

            Set MBeanset = mbsc.queryMBeans(null, null);
            //System.out.println("加载类数量 : " + MBeanset.size());
            tomcatVo.setBeanSize(MBeanset.size());
            // Iterator MBeansetIterator = MBeanset.iterator();
            // while (MBeansetIterator.hasNext()) {
            //     ObjectInstance objectInstance = (ObjectInstance) MBeansetIterator.next();
            //     ObjectName objectName = objectInstance.getObjectName();
            //     String canonicalName = objectName.getCanonicalName();
            //     System.out.println("canonicalName : " + canonicalName);
            //     if (canonicalName.equals("Catalina:host=localhost,type=Cluster")) {
            //         // Get details of cluster MBeans
            //         System.out.println("Cluster MBeans Details:");
            //         System.out.println("=========================================");
            //         //getMBeansDetails(canonicalName);
            //         String canonicalKeyPropList = objectName.getCanonicalKeyPropertyListString();
            //     }
            // }

            //------------------------- system ----------------------
            ObjectName runtimeObjName = new ObjectName("java.lang:type=Runtime");
            // System.out.println("厂商:" + mbsc.getAttribute(runtimeObjName, "VmVendor"));
            // System.out.println("程序:" + mbsc.getAttribute(runtimeObjName, "VmName"));
            // System.out.println("版本:" + mbsc.getAttribute(runtimeObjName, "VmVersion"));
            Date starttime = new Date((Long) mbsc.getAttribute(runtimeObjName, "StartTime"));
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // System.out.println("启动时间:" + df.format(starttime));
            tomcatVo.setStartTime(df.format(starttime));
            Long timespan = (Long) mbsc.getAttribute(runtimeObjName, "Uptime");
            // System.out.println("连续工作时间:" + formatTimeSpan(timespan));
            tomcatVo.setTimeSpan(formatTimeSpan(timespan));

            //------------------------ JVM -------------------------
            //堆使用率
            ObjectName heapObjName = new ObjectName("java.lang:type=Memory");
            MemoryUsage heapMemoryUsage = MemoryUsage.from((CompositeDataSupport) mbsc.getAttribute(heapObjName, "HeapMemoryUsage"));
            // long maxMemory = heapMemoryUsage.getMax();
            long commitMemory = heapMemoryUsage.getCommitted();
            long usedMemory = heapMemoryUsage.getUsed();
            // long initMemory = heapMemoryUsage.getInit();
            // System.out.println("已使用的堆内存量: " + usedMemory / 1024 / 1024 + "M");
            // System.out.println("已提交的堆内存量: " + commitMemory / 1024 / 1024 + "M");
            // System.out.println("初始化的堆内存量: " + initMemory / 1024 / 1024 + "M");
            // System.out.println("堆内存的最大值: " + maxMemory / 1024 / 1024 + "M");
            // System.out.println("堆内存使用率:" + usedMemory * 100 / commitMemory + "%");
            tomcatVo.setUsedMemory(usedMemory / 1024 / 1024 + "M");
            tomcatVo.setCommitMemory(commitMemory / 1024 / 1024 + "M");
            tomcatVo.setPerMemory(usedMemory * 100 / commitMemory + "%");
            // MemoryUsage nonheapMemoryUsage = MemoryUsage.from((CompositeDataSupport) mbsc.getAttribute(heapObjName, "NonHeapMemoryUsage"));
            // long noncommitMemory = nonheapMemoryUsage.getCommitted();
            // long nonusedMemory = heapMemoryUsage.getUsed();
            // System.out.println("非堆内存使用率:" + nonusedMemory * 100 / noncommitMemory + "%");
            //内存池
            // ObjectName permObjName = new ObjectName("java.lang:type=MemoryPool,*");
            // Set<ObjectName> s0 = mbsc.queryNames(permObjName, null);
            // for (ObjectName obj : s0) {
            //     MemoryPoolMXBean poolBean = ManagementFactory.newPlatformMXBeanProxy(
            //             mbsc, obj.getCanonicalName(), MemoryPoolMXBean.class);
            //     MemoryUsage usage = poolBean.getUsage(); // 获取当前使用情况
            //     System.out.println("内存池名称: " + obj.getKeyProperty("name"));
            //     System.out.println("    当前已使用的内存量: " + usage.getUsed() / 1024 / 1024 + "M");
            //     System.out.println("    JVM为内存池预留的内存量: " + usage.getCommitted() / 1024 / 1024 + "M");
            //     System.out.println("    内存池初始化时的内存量: " + usage.getInit() / 1024 / 1024 + "M");
            //     System.out.println("    内存池可达到的最大内存量: " + usage.getMax() / 1024 / 1024 + "M");
            // }

            //-------------------- Session ---------------
            // ObjectName managerObjName = new ObjectName("Catalina:type=Manager,*");
            // Set<ObjectName> s1 = mbsc.queryNames(managerObjName, null);
            // for (ObjectName obj : s1) {
            //     System.out.println("应用名:" + obj.getKeyProperty("name"));
            //     ObjectName objname = new ObjectName(obj.getCanonicalName());
            //     System.out.println("最大会话数:" + mbsc.getAttribute(objname, "maxActiveSessions"));
            //     System.out.println("会话数:" + mbsc.getAttribute(objname, "activeSessions"));
            //     System.out.println("活动会话数:" + mbsc.getAttribute(objname, "sessionCounter"));
            // }
            //----------------- Thread Pool ----------------
            ObjectName threadpoolObjName = new ObjectName("Catalina:type=ThreadPool,*");
            Set<ObjectName> s2 = mbsc.queryNames(threadpoolObjName, null);
            int maxThreads = 0;
            int currentThreadCount = 0;
            for (ObjectName obj : s2) {
                // System.out.println("端口名:" + obj.getKeyProperty("name"));
                ObjectName objname = new ObjectName(obj.getCanonicalName());
                // System.out.println("最大线程数:" + mbsc.getAttribute(objname, "maxThreads"));
                // System.out.println("当前线程数:" + mbsc.getAttribute(objname, "currentThreadCount"));
                // System.out.println("繁忙线程数:" + mbsc.getAttribute(objname, "currentThreadsBusy"));
                if (obj.getKeyProperty("name").indexOf("http") >= 0) {
                    tomcatVo.setPort(obj.getKeyProperty("name"));
                }
                maxThreads += (Integer) mbsc.getAttribute(objname, "maxThreads");
                currentThreadCount += (Integer) mbsc.getAttribute(objname, "currentThreadCount");
            }
            tomcatVo.setMaxThreads(maxThreads);
            tomcatVo.setCurrentThreadCount(currentThreadCount);

            ObjectName osName = new ObjectName("java.lang:type=OperatingSystem");
            Object result = mbsc.getAttribute(osName, "SystemCpuLoad");
            // System.out.println("CPU负载信息: " + result);
            DecimalFormat ndf = new DecimalFormat("0.00");
            tomcatVo.setSystemCpuLoad(ndf.format(result));

            connector.close();
        } catch (Exception e) {
            //System.out.println("获取信息失败:" + appVo.getName());
            // logger.error("客户端 -> 获取Tomcat信息错误\n{}", e.getMessage());
            tomcatVo.setState(0);
            logger.info("客户端 -> 获取Tomcat信息失败");
            return tomcatVo;
        }
        logger.info("客户端 -> 获取Tomcat信息成功\n{}", JSONUtil.toJsonStr(tomcatVo));
        return tomcatVo;
    }

    public static String formatTimeSpan(long span) {
        long minseconds = span % 1000;

        span = span / 1000;
        long seconds = span % 60;

        span = span / 60;
        long mins = span % 60;

        span = span / 60;
        long hours = span % 24;

        span = span / 24;
        long days = span;
        return (new Formatter()).format("%1$d天 %2$02d:%3$02d:%4$02d.%5$03d", days, hours, mins, seconds, minseconds)
                .toString();
    }
}
